package com.example.fpe_vote.db1.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.fpe_vote.common.Result;
import com.example.fpe_vote.db1.entity.NomineeInfo;
import com.example.fpe_vote.db1.entity.PrizeInfo;
import com.example.fpe_vote.db1.entity.VoteInfo;
import com.example.fpe_vote.db1.service.INomineeInfoService;
import com.example.fpe_vote.db1.service.IPrizeInfoService;
import com.example.fpe_vote.db1.service.IVoteInfoService;
import com.example.fpe_vote.utils.MyFileUtil;
import com.example.fpe_vote.utils.MyStringUtil;
import com.example.fpe_vote.vo.request.RequestGetNomineeVo;
import com.example.fpe_vote.vo.response.ResponseGetNomineeVo;
import com.example.fpe_vote.vo.response.ResponseViewNomineeVo;
import com.example.fpe_vote.vo.response.ResponseVoteResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-12-01
 */
@RestController
@RequestMapping("/nominee-info")
public class NomineeInfoController {
    @Autowired
    INomineeInfoService nomineeInfoService;
    @Autowired
    IVoteInfoService voteInfoService;
    @Autowired
    IPrizeInfoService prizeInfoService;
    @Value("${file.nginxIp}")
    private String nginxIp;
    @Value("${file.pathName}")
    private String path;

    //获取提名人列表
    @PostMapping("/getNominee")
    public Result getNominee(@RequestBody RequestGetNomineeVo vo){
        List<ResponseGetNomineeVo> voList=new ArrayList<>();
        QueryWrapper<NomineeInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("prize_num",vo.getPrizeNum());
        List<NomineeInfo> list= nomineeInfoService.list(queryWrapper);
        if(list==null||list.size()==0){
            return Result.getFailure().setMsg("当前奖项目前还没有任何提名人,请等待...");
        }else {
            for (NomineeInfo nomineeInfo : list) {
                ResponseGetNomineeVo responseGetNomineeVo = new ResponseGetNomineeVo();
                BeanUtils.copyProperties(nomineeInfo, responseGetNomineeVo);
                responseGetNomineeVo.setNginxIp(nginxIp);
                voList.add(responseGetNomineeVo);
            }
            return Result.getSuccess().setData(voList);
        }
    }

    //新增提名人
    @RequestMapping("/addNominee")
    @ResponseBody
    public Result addNominee(@RequestParam MultipartFile file, HttpServletRequest request ) throws Exception{
        //得到前端传来的参数
        String userName=request.getParameter("userName").replace(" ","");
        String zwName=request.getParameter("zwName").replace(" ","");
        String prizeNum=request.getParameter("prizeNum").replace(" ","");
        String introduce=request.getParameter("introduce").replace(" ","");
        if(userName==null||zwName==null||prizeNum==null||introduce==null||Objects.equals(introduce, "")|| Objects.equals(userName, "") || Objects.equals(zwName, "") || Objects.equals(prizeNum, "")){
            return Result.getFailure().setMsg("信息不完整！请确认...");
        }
        if(ObjectUtils.isNotEmpty(nomineeInfoService.queryByInfo(userName,zwName,prizeNum))){
            return Result.getFailure().setMsg("该奖项已经提名该员工！禁止重复提名！");
        }else {
            String fileName;
            fileName=zwName+"-"+userName+"-照片"+ IdWorker.getIdStr();
            String issueAffix = null;
            if (file != null && !file.isEmpty()){
                if ((issueAffix = MyFileUtil.handleFormUpload(file,fileName,path)) != null) {
                    //获取文件原始名称
                    String originalFilename = file.getOriginalFilename();
                    //分割后缀
                    String[] filename = originalFilename.split("\\.");
                    //保存
                    NomineeInfo nomineeInfo=new NomineeInfo();
                    nomineeInfo.setName(userName);
                    nomineeInfo.setPhoto("VoteFile/"+fileName+"."+filename[1]);
                    nomineeInfo.setPrizeNum(prizeNum);
                    nomineeInfo.setZwname(zwName);
                    nomineeInfo.setIntroduce(introduce);
                    nomineeInfoService.save(nomineeInfo);
                    return Result.getSuccess().setMsg("提名成功!");
                } else if(Objects.equals(MyFileUtil.handleFormUpload(file,fileName,path), "exist")) {
                    System.err.println("提名失败!");
                    return Result.getFailure().setMsg("提名失败,重复提交!");
                }else{
                    System.err.println("文件,上传失败!");
                    return Result.getFailure().setMsg("上传失败!");
                }
            }else
                return Result.getFailure().setMsg("文件为空");
        }
    }


    //查看该奖项提名人
    @GetMapping("/viewNominee/{prizeNum}")
    public Result viewNominee(@PathVariable String prizeNum){
        QueryWrapper<NomineeInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("prize_num",prizeNum);
        List<NomineeInfo> list=nomineeInfoService.list(queryWrapper);
        if(list.size()==0){
            return Result.getFailure().setMsg("未提名任何人..");
        }
        List<ResponseViewNomineeVo> voList=new ArrayList<>();
        for(NomineeInfo nomineeInfo:list){
            ResponseViewNomineeVo viewNomineeVo=new ResponseViewNomineeVo();
            BeanUtils.copyProperties(nomineeInfo,viewNomineeVo);
            voList.add(viewNomineeVo);
        }
        return Result.getSuccess().setData(voList);
    }

    //投票结果查询
    @GetMapping("/voteResult/{prizeNum}")
    public Result voteResult(@PathVariable String prizeNum){
        QueryWrapper<NomineeInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("prize_num",prizeNum);
        List<NomineeInfo> nomineeInfoList=nomineeInfoService.list(queryWrapper);
        String[] names=new String[nomineeInfoList.size()];
        Long[] counts=new Long[nomineeInfoList.size()];
        for(int i=0;i<nomineeInfoList.size();i++){
            names[i]=nomineeInfoList.get(i).getName();
            counts[i]= Long.valueOf(nomineeInfoList.get(i).getVotes());
        }
        //排序
        ResponseVoteResultVo vo=MyStringUtil.BubbleSort2(counts,names);
        PrizeInfo prizeInfo=prizeInfoService.queryByNum(prizeNum);
        vo.setAllowAmounts(prizeInfo.getAllowAmounts());
        return Result.getSuccess().setData(vo);
    }

}
